<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>在线留言 - 印象滑州网</title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css">
    <style>
        :root {
            --primaryBlue: #007BFF;
            --secondaryBlue: #0056b3;
            --lightBlue: #e7f5ff;
            --starBlue: #2A4359;
            --ink: #333333;
            --jade: #F7FBFE;
            --autumnBlue: #8AA2B5;
            --glazeBlue: #3A5F7D;
            --paleBlueGrey: #E1E8ED;
            --stoneGreen: #5C877B;
            --bambooGreen: #7A9D8F;
           
        }

        * { margin: 0; padding: 0; box-sizing: border-box; }
        body {
            font-family: "Microsoft YaHei", "PingFang SC", sans-serif;
            line-height: 1.6;
            color: var(--ink);
            background-color: var(--jade);
        }
        
        /* 导航栏样式 */
        .nav-container {
            background-color: rgba(247, 251, 254, 0.95);
            padding: 1.2rem 3rem;
            display: flex;
            justify-content: space-between;
            align-items: center;
            box-shadow: 0 2px 20px rgba(0,0,0,0.05);
            position: fixed;
            width: 100%;
            top: 0;
            z-index: 1000;
            transition: all 0.3s ease;
            backdrop-filter: blur(10px);
        }
        
        .logo { display: flex; align-items: center; gap: 1rem; }
        
        .logo-icon {
            width: 80px; height: 80px; background: transparent; border-radius: 50%;
            display: flex; align-items: center; justify-content: center; transition: all 0.3s ease;
        }
        
        .logo-icon img { width: 100%; height: 100%; object-fit: contain; }
        
        .logo h1 {
            color: var(--starBlue);
            font-size: 1.8rem;
            font-weight: 600;
            letter-spacing: 1px;
            background: linear-gradient(45deg, var(--primaryBlue), var(--glazeBlue));
            -webkit-background-clip: text;
            -webkit-text-fill-color: transparent;
        }
        
        .nav-links {
            display: flex;
            list-style: none;
            gap: 2.5rem;
        }
        
        .nav-links a {
            color: var(--starBlue);
            text-decoration: none;
            font-size: 1.1rem;
            padding: 0.5rem 1rem;
            border-radius: 4px;
            transition: all 0.3s ease;
            position: relative;
        }
        
        .nav-links a::after {
            content: '';
            position: absolute;
            bottom: 0;
            left: 50%;
            width: 0;
            height: 2px;
            background: linear-gradient(90deg, var(--primaryBlue), var(--bambooGreen));
            transition: all 0.3s ease;
            transform: translateX(-50%);
        }
        
        .nav-links a:hover::after,
        .nav-links a.active::after { width: 100%; }
        
        .nav-links a:hover,
        .nav-links a.active { color: var(--primaryBlue); }

        /* 留言区头部样式 */
        .message-hero {
            height: 60vh;
            background: linear-gradient(135deg, var(--starBlue), var(--glazeBlue));
            display: flex;
            align-items: center;
            justify-content: center;
            text-align: center;
            color: var(--jade);
            margin-top: 80px;
            position: relative;
            overflow: hidden;
        }
        
        .message-hero::before {
    content: '';
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background: url('https://img2.baidu.com/it/u=55765027,1142004606&fm=253&fmt=auto&app=138&f=JPEG?w=1200&h=800');
    opacity: 0.55;
    background-size: cover;      /* 新增：使背景图覆盖整个容器 */
    background-position: center; /* 新增：将背景图居中显示 */
    background-repeat: no-repeat; /* 新增：防止背景图重复 */
}
        
        .message-hero-content { position: relative; z-index: 1; }
        
        .message-hero h2 {
            font-size: 3.5rem;
            margin-bottom: 1rem;
            text-shadow: 2px 2px 4px rgba(0,0,0,0.3);
        }
        
        .message-hero p {
            font-size: 1.5rem;
            max-width: 800px;
            margin: 0 auto;
            text-shadow: 1px 1px 2px rgba(0,0,0,0.3);
        }

        /* 留言表单区域 */
        .message-container {
            max-width: 1200px;
            margin: 0 auto;
            padding: 4rem 2rem;
        }
        
        .message-form-section {
            background-color: white;
            padding: 3rem;
            border-radius: 8px;
            box-shadow: 0 10px 30px rgba(0,0,0,0.05);
            margin-bottom: 4rem;
            position: relative;
        }
        
        .message-form-title {
            text-align: center;
            margin-bottom: 2rem;
            position: relative;
        }
        
        .message-form-title h3 {
            font-size: 1.8rem;
            color: var(--primaryBlue);
            display: inline-block;
            padding: 0 1rem;
            background-color: white;
            position: relative;
            z-index: 1;
        }
        
        .message-form-title::before {
            content: "";
            position: absolute;
            top: 50%;
            left: 0;
            right: 0;
            height: 1px;
            background-color: var(--paleBlueGrey);
            z-index: 0;
        }
        
        /* 管理员登录链接 */
        .admin-login-link {
            position: absolute;
            top: 3rem;
            right: 3rem;
            color: var(--primaryBlue);
            cursor: pointer;
            font-size: 0.95rem;
            text-decoration: none;
            transition: color 0.3s;
        }
        
        .admin-login-link:hover {
            color: var(--glazeBlue);
        }
        
        .message-form {
            display: grid;
            grid-template-columns: 1fr;
            gap: 1.5rem;
        }
        
        .form-group {
            margin-bottom: 1.5rem;
        }
        
        .form-group label {
            display: block;
            margin-bottom: 0.5rem;
            color: var(--starBlue);
            font-weight: 500;
        }
        
        .form-group input,
        .form-group textarea {
            width: 100%;
            padding: 0.8rem;
            border: 1px solid var(--paleBlueGrey);
            border-radius: 8px;
            font-size: 1rem;
            transition: border-color 0.3s;
        }
        
        .form-group input:focus,
        .form-group textarea:focus {
            outline: none;
            border-color: var(--primaryBlue);
            box-shadow: 0 0 0 2px rgba(0, 123, 255, 0.25);
        }
        
        .form-group textarea {
            resize: vertical;
            min-height: 120px;
        }
        
        /* 验证码区域 */
        .captcha-group {
            display: flex;
            gap: 1rem;
        }
        
        .captcha-group input {
            flex: 1;
        }
        
        .captcha-image {
            width: 150px;
            height: 40px;
            background-color: var(--paleBlueGrey);
            border: 1px solid var(--paleBlueGrey);
            border-radius: 8px;
            display: flex;
            align-items: center;
            justify-content: center;
            cursor: pointer;
            transition: all 0.3s;
        }
        
        .captcha-image:hover {
            box-shadow: 0 0 5px rgba(0, 0, 0, 0.1);
        }
        
        /* 按钮样式 */
        .message-form button {
            background-color: var(--primaryBlue);
            color: white;
            border: none;
            padding: 0.8rem 2rem;
            font-size: 1.1rem;
            border-radius: 8px;
            cursor: pointer;
            transition: background-color 0.3s;
            text-align: center;
            display: inline-block;
            margin: 0 auto;
            width: auto;
            justify-self: center;
        }
        
        .message-form button:hover {
            background-color: var(--glazeBlue);
        }
        
        /* 纹理分割线 */
        .divider {
            height: 60px;
            margin: 3rem 0;
            background-image: url("data:image/svg+xml,%3Csvg width='100' height='30' viewBox='0 0 100 30' xmlns='http://www.w3.org/2000/svg'%3E%3Cpath d='M0 10c25 0 25-10 50-10s25 10 50 10 25-10 50-10V0c-25 0-25 10-50 10S25 0 0 0v10zm0 20c25 0 25-10 50-10s25 10 50 10 25-10 50-10v-10c-25 0-25 10-50 10S25 10 0 10v10z' fill='%23007BFF' fill-opacity='0.1' fill-rule='evenodd'/%3E%3C/svg%3E");
            background-repeat: repeat-x;
            background-position: center;
        }
        
        /* 留言展示区域 */
        .message-list-section {
            background-color: white;
            padding: 3rem;
            border-radius: 8px;
            box-shadow: 0 10px 30px rgba(0,0,0,0.05);
        }
        
        .message-list-title {
            text-align: center;
            margin-bottom: 2rem;
            position: relative;
        }
        
        .message-list-title h3 {
            font-size: 1.8rem;
            color: var(--primaryBlue);
            display: inline-block;
            padding: 0 1rem;
            background-color: white;
            position: relative;
            z-index: 1;
        }
        
        .message-list-title::before {
            content: "";
            position: absolute;
            top: 50%;
            left: 0;
            right: 0;
            height: 1px;
            background-color: var(--paleBlueGrey);
            z-index: 0;
        }
        
        .message-items {
            display: flex;
            flex-direction: column;
            gap: 2rem;
        }
        
        .message-item {
            padding: 1.5rem;
            border: 1px solid var(--paleBlueGrey);
            border-radius: 8px;
            position: relative;
            transition: all 0.3s;
        }
        
        .message-item:hover {
            box-shadow: 0 5px 15px rgba(0, 0, 0, 0.05);
        }
        
        .message-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 1rem;
            padding-bottom: 0.5rem;
            border-bottom: 1px dashed var(--paleBlueGrey);
        }
        
        .message-author {
            color: var(--primaryBlue);
            font-weight: 500;
        }
        
        .message-date {
            color: var(--autumnBlue);
            font-size: 0.9rem;
        }
        
        .message-content {
            color: var(--ink);
            margin-bottom: 1rem;
        }
        
        .message-reply {
            background-color: var(--lightBlue);
            padding: 1rem;
            border-radius: 8px;
            border-left: 3px solid var(--primaryBlue);
        }
        
        .message-reply-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 0.5rem;
        }
        
        .message-reply-author {
            color: var(--primaryBlue);
            font-weight: 500;
        }
        
        .message-reply-date {
            color: var(--autumnBlue);
            font-size: 0.9rem;
        }
        
        .message-reply-content {
            color: var(--ink);
        }
        
        /* 管理员回复表单 */
        .admin-reply-form {
            margin-top: 1rem;
            padding: 1rem;
            background-color: var(--lightBlue);
            border-radius: 8px;
        }
        
        .admin-reply-form textarea {
            width: 100%;
            padding: 0.8rem;
            border: 1px solid var(--paleBlueGrey);
            border-radius: 8px;
            font-size: 1rem;
            margin-bottom: 0.5rem;
        }
        
        .admin-reply-form button {
            background-color: var(--primaryBlue);
            color: white;
            border: none;
            padding: 0.5rem 1.5rem;
            font-size: 0.95rem;
            border-radius: 8px;
            cursor: pointer;
            transition: background-color 0.3s;
        }
        
        .admin-reply-form button:hover {
            background-color: var(--glazeBlue);
        }
        
        /* 分页控件 */
        .pagination {
            display: flex;
            justify-content: center;
            align-items: center;
            margin-top: 2rem;
            gap: 0.5rem;
        }
        
        .pagination button {
            background-color: white;
            color: var(--primaryBlue);
            border: 1px solid var(--paleBlueGrey);
            padding: 0.5rem 1rem;
            border-radius: 8px;
            cursor: pointer;
            transition: all 0.3s;
        }
        
        .pagination button:hover {
            background-color: var(--primaryBlue);
            color: white;
            border-color: var(--primaryBlue);
        }
        
        .pagination button.active {
            background-color: var(--primaryBlue);
            color: white;
            border-color: var(--primaryBlue);
        }
        
        /* 页脚样式 */
        footer {
            background: linear-gradient(135deg, var(--starBlue), var(--glazeBlue));
            color: var(--jade);
            padding: 3rem 2rem;
            text-align: center;
        }
        
        .footer-content p { font-size: 1rem; opacity: 0.8; }
        
        /* 登录弹窗样式 */
        .login-modal {
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background-color: rgba(0, 0, 0, 0.5);
            display: flex;
            justify-content: center;
            align-items: center;
            z-index: 2000;
            opacity: 0;
            pointer-events: none;
            transition: opacity 0.3s;
        }
        
        .login-modal.active {
            opacity: 1;
            pointer-events: auto;
        }
        
        .login-modal-content {
            background-color: white;
            border-radius: 8px;
            box-shadow: 0 10px 30px rgba(0, 0, 0, 0.2);
            width: 350px;
            max-width: 90%;
            transform: scale(0.9);
            transition: transform 0.3s;
        }
        
        .login-modal.active .login-modal-content {
            transform: scale(1);
        }
        
        .login-modal-header {
            padding: 1.5rem;
            border-bottom: 1px solid var(--paleBlueGrey);
            display: flex;
            justify-content: space-between;
            align-items: center;
        }
        
        .login-modal-header h3 {
            color: var(--primaryBlue);
            font-size: 1.3rem;
        }
        
        .login-modal-close {
            font-size: 1.5rem;
            color: var(--autumnBlue);
            cursor: pointer;
            transition: color 0.3s;
        }
        
        .login-modal-close:hover {
            color: var(--starBlue);
        }
        
        .login-modal-body {
            padding: 1.5rem;
        }
        
        .login-form-group {
            margin-bottom: 1.2rem;
        }
        
        .login-form-group label {
            display: block;
            margin-bottom: 0.5rem;
            color: var(--starBlue);
            font-weight: 500;
        }
        
        .login-form-group input {
            width: 100%;
            padding: 0.8rem;
            border: 1px solid var(--paleBlueGrey);
            border-radius: 8px;
            font-size: 1rem;
            transition: border-color 0.3s;
        }
        
        .login-form-group input:focus {
            outline: none;
            border-color: var(--primaryBlue);
            box-shadow: 0 0 0 2px rgba(0, 123, 255, 0.25);
        }
        
        .login-modal-footer {
            padding: 0 1.5rem 1.5rem 1.5rem;
        }
        
        .login-modal-footer button {
            background-color: var(--primaryBlue);
            color: white;
            border: none;
            padding: 0.8rem 2rem;
            font-size: 1rem;
            border-radius: 8px;
            cursor: pointer;
            transition: background-color 0.3s;
            width: 100%;
        }
        
        .login-modal-footer button:hover {
            background-color: var(--glazeBlue);
        }
        
        .login-error {
            color: var(--imperialRed);
            margin-bottom: 1rem;
            text-align: center;
            display: none;
        }
        
        /* 响应式设计 */
        @media (max-width: 768px) {
            .nav-container { padding: 1rem; flex-direction: column; }
            .nav-links { margin-top: 1rem; flex-direction: column; align-items: center; gap: 1rem; }
            .message-hero h2 { font-size: 2.5rem; }
            .message-hero p { font-size: 1.2rem; }
            .message-container { padding: 2rem 1rem; }
            .message-form-section, .message-list-section { padding: 2rem 1rem; }
            .captcha-group { flex-direction: column; }
            .captcha-image { width: 100%; }
            .admin-login-link {
                top: 2rem;
                right: 2rem;
            }
        }
    </style>
</head>
<body>
    <header>
        <nav class="nav-container">
            <div class="logo">
                <div class="logo-icon">
                    <img src="hz.png" alt="滑州网logo">
                </div>
                <h1>印象滑州网</h1>
            </div>
            <ul class="nav-links">
                <li><a href="index.html">首页</a></li>
                <li><a href="food.html">美食介绍</a></li>
                <li><a href="scenery.html">景点介绍</a></li>
                <li><a href="culture.html">民俗文化</a></li>
                <li><a href="message.html" class="active">在线留言</a></li>
            </ul>
        </nav>
    </header>
    
    <main>
        <section class="message-hero">
            <div class="message-hero-content">
                <h2>在线留言</h2>
                <p>欢迎留言交流，您的建议是我们前进的动力</p>
            </div>
        </section>
        
        <section class="message-container">
            <!-- 留言表单区域 -->
            <div class="message-form-section">
                <div class="message-form-title">
                    <h3>留言板</h3>
                </div>
                
                <!-- 管理员登录链接 -->
                <div class="admin-login-link" id="adminLoginLink">管理员登录</div>
                
                <form class="message-form" id="messageForm">
                    <div class="form-group">
                        <label for="content">留言内容</label>
                        <textarea id="content" rows="5" placeholder="请输入您的留言内容..." required></textarea>
                    </div>
                    
                    <div class="form-group">
                        <label for="email">邮箱</label>
                        <input type="email" id="email" placeholder="请输入您的邮箱地址..." required>
                    </div>
                    
                    <div class="form-group captcha-group">
                        <label>验证码</label>
                        <input type="text" placeholder="请输入验证码..." required>
                        <div class="captcha-image" id="captchaImage">
                            <span id="captchaText">点击刷新</span>
                        </div>
                    </div>
                    
                    <button type="submit">提交留言</button>
                </form>
            </div>
            
            <!-- 纹理分割线 -->
            <div class="divider"></div>
            
            <!-- 留言展示区域 -->
            <div class="message-list-section">
                <div class="message-list-title">
                    <h3>留言列表</h3>
                </div>
                
                <div class="message-items" id="messageList"></div>
                
                <!-- 分页控件 -->
                <div class="pagination" id="pagination"></div>
            </div>
        </section>
    </main>
    
    <footer>
        <div class="footer-content">
            <p>&copy; 2025 印象滑州网 版权所有</p>
        </div>
    </footer>
    
    <!-- 管理员登录弹窗 -->
    <div class="login-modal" id="loginModal">
        <div class="login-modal-content">
            <div class="login-modal-header">
                <h3>管理员登录</h3>
                <div class="login-modal-close" id="loginModalClose">&times;</div>
            </div>
            <div class="login-modal-body">
                <div class="login-error" id="loginError">用户名或密码错误</div>
                <form id="loginForm">
                    <div class="login-form-group">
                        <label for="username">用户名</label>
                        <input type="text" id="username" placeholder="请输入用户名" required>
                    </div>
                    <div class="login-form-group">
                        <label for="password">密码</label>
                        <input type="password" id="password" placeholder="请输入密码" required>
                    </div>
                </form>
            </div>
            <div class="login-modal-footer">
                <button type="button" id="loginButton">登录</button>
            </div>
        </div>
    </div>

    <script>
      // 状态变量
let messages = [];
let currentPage = 1;
const pageSize = 3;
let isAdminLoggedIn = false;

// 初始化应用
function initApp() {
    // 加载留言
    loadMessages();
    
    // 初始化验证码
    generateCaptcha();
    
    // 绑定事件
    bindEvents();
    
    // 检查管理员登录状态
    checkAdminLoginStatus();
}

// 绑定事件处理函数
function bindEvents() {
    // 点击刷新验证码
    document.getElementById('captchaImage').addEventListener('click', generateCaptcha);
    
    // 提交留言
    document.getElementById('messageForm').addEventListener('submit', async function(e) {
        e.preventDefault();
        
        const content = document.getElementById('content').value.trim();
        const email = document.getElementById('email').value.trim();
        const captchaInput = this.querySelector('.captcha-group input').value.trim();
        const captchaText = document.getElementById('captchaText').textContent;
        
        if (!content || !email || !captchaInput) {
            showNotification('请填写完整信息', 'error');
            return;
        }
        
        if (captchaInput !== captchaText) {
            showNotification('验证码错误', 'error');
            generateCaptcha();
            return;
        }
        
        try {
            // 创建新留言
            const response = await fetch('http://localhost:3000/messages', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({ 
                    content, 
                    email, 
                    date: new Date().toISOString().split('T')[0],
                    reply: null,
                    replyDate: null
                })
            });
            
            if (!response.ok) {
                throw new Error(`创建留言失败: ${response.status}`);
            }
            
            // 重置表单
            this.reset();
            generateCaptcha();
            
            // 更新列表
            currentPage = 1; // 重置到第一页
            loadMessages();
            
            // 显示成功提示
            showNotification('留言提交成功！我们会尽快回复您。');
        } catch (error) {
            console.error('提交留言失败:', error);
            showNotification('提交留言失败，请稍后再试', 'error');
        }
    });
    
    // 管理员登录链接点击事件
    document.getElementById('adminLoginLink').addEventListener('click', () => {
        if (isAdminLoggedIn) {
            logoutAdmin();
        } else {
            openLoginModal();
        }
    });
    
    // 关闭登录弹窗
    document.getElementById('loginModalClose').addEventListener('click', closeLoginModal);
    
    // 登录按钮点击事件
    document.getElementById('loginButton').addEventListener('click', handleLogin);
    
    // 登录表单提交事件
    document.getElementById('loginForm').addEventListener('submit', function(e) {
        e.preventDefault();
        handleLogin();
    });
}

// 生成随机验证码
function generateCaptcha() {
    const chars = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ';
    let captcha = '';
    for (let i = 0; i < 4; i++) {
        captcha += chars.charAt(Math.floor(Math.random() * chars.length));
    }
    
    document.getElementById('captchaText').textContent = captcha;
    
    
}

// 加载留言
async function loadMessages() {
    try {
        // 从服务器获取数据
        const response = await fetch('http://localhost:3000/messages');
        
        if (!response.ok) {
            throw new Error(`获取留言失败: ${response.status}`);
        }
        
        messages = await response.json();
        
        // 确保数据格式统一
        messages = messages.map(msg => ({
            id: msg.id,
            content: msg.content || '',
            email: msg.email || '',
            date: msg.date || (msg.createdAt ? msg.createdAt.split('T')[0] : new Date().toISOString().split('T')[0]),
            reply: msg.reply || null,
            replyDate: msg.replyDate || null
        }));
        
        // 渲染留言列表
        renderMessageList();
        
        // 渲染分页控件
        renderPagination();
    } catch (error) {
        console.error('加载留言失败:', error);
        showNotification('加载留言失败，请稍后再试', 'error');
        
        
        
        renderMessageList();
        renderPagination();
    }
}

// 渲染留言列表
function renderMessageList() {
    const messageListElement = document.getElementById('messageList');
    messageListElement.innerHTML = '';
    
    // 计算当前页显示的留言
    const startIndex = (currentPage - 1) * pageSize;
    const endIndex = Math.min(startIndex + pageSize, messages.length);
    const currentMessages = messages.slice(startIndex, endIndex);
    
    if (currentMessages.length === 0) {
        messageListElement.innerHTML = '<div class="text-center text-gray-500">暂无留言，请先留言</div>';
        return;
    }
    
    currentMessages.forEach(message => {
        const messageElement = document.createElement('div');
        messageElement.className = 'message-item';
        messageElement.innerHTML = `
            <div class="message-header">
                <div class="message-author">网友留言</div>
                <div class="message-date">${message.date}</div>
            </div>
            <div class="message-content">${message.content}</div>
            
            ${message.reply ? `
                <div class="message-reply">
                    <div class="message-reply-header">
                        <div class="message-reply-author">管理员回复</div>
                        <div class="message-reply-date">${message.replyDate}</div>
                    </div>
                    <div class="message-reply-content">${message.reply}</div>
                </div>
            ` : ''}
            
            ${isAdminLoggedIn && !message.reply ? `
                <div class="admin-reply-form">
                    <textarea placeholder="请输入回复内容" data-message-id="${message.id}"></textarea>
                    <button class="reply-button" data-message-id="${message.id}">回复</button>
                </div>
            ` : ''}
        `;
        
        messageListElement.appendChild(messageElement);
    });
    
    // 为回复按钮绑定事件
    bindReplyButtons();
}

// 单独的函数用于绑定回复按钮事件
function bindReplyButtons() {
    document.querySelectorAll('.reply-button').forEach(button => {
        button.addEventListener('click', async function() {
            const messageId = this.getAttribute('data-message-id');
            const textarea = this.parentElement.querySelector('textarea');
            const replyContent = textarea.value.trim();
            
            if (!replyContent) {
                showNotification('请输入回复内容', 'error');
                return;
            }
            
            try {
                // 找到要回复的留言
                const messageToUpdate = messages.find(msg => msg.id === messageId);
                
                if (!messageToUpdate) {
                    throw new Error('找不到要回复的留言');
                }
                
                // 构建更新数据 - 包含原留言的所有字段和新回复
                const updateData = {
                    ...messageToUpdate, // 保留原留言的所有字段
                    reply: replyContent,
                    replyDate: new Date().toISOString().split('T')[0]
                };
                
                // 发送PUT请求更新留言回复
                const response = await fetch(`http://localhost:3000/messages/${messageId}`, {
                    method: 'PUT',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify(updateData)
                });
                
                if (!response.ok) {
                    throw new Error(`服务器响应错误: ${response.status}`);
                }
                
                // 获取更新后的完整数据
                const updatedMessage = await response.json();
                
                // 更新本地数据
                messages = messages.map(msg => 
                    msg.id === messageId ? updatedMessage : msg
                );
                
                // 刷新留言列表
                renderMessageList();
                showNotification('回复成功');
            } catch (error) {
                console.error('回复失败:', error);
                showNotification('回复失败，请稍后再试', 'error');
            }
        });
    });
}

// 渲染分页控件
function renderPagination() {
    const paginationElement = document.getElementById('pagination');
    paginationElement.innerHTML = '';
    
    const totalPages = Math.ceil(messages.length / pageSize);
    
    if (totalPages <= 1) return;
    
    // 上一页按钮
    const prevButton = document.createElement('button');
    prevButton.innerHTML = '<i class="fa fa-angle-left"></i>';
    prevButton.disabled = currentPage === 1;
    prevButton.addEventListener('click', () => {
        if (currentPage > 1) {
            currentPage--;
            loadMessages();
        }
    });
    paginationElement.appendChild(prevButton);
    
    // 页码按钮
    for (let i = 1; i <= totalPages; i++) {
        const pageButton = document.createElement('button');
        pageButton.textContent = i;
        pageButton.classList.toggle('active', i === currentPage);
        pageButton.addEventListener('click', () => {
            currentPage = i;
            loadMessages();
        });
        paginationElement.appendChild(pageButton);
    }
    
    // 下一页按钮
    const nextButton = document.createElement('button');
    nextButton.innerHTML = '<i class="fa fa-angle-right"></i>';
    nextButton.disabled = currentPage === totalPages;
    nextButton.addEventListener('click', () => {
        if (currentPage < totalPages) {
            currentPage++;
            loadMessages();
        }
    });
    paginationElement.appendChild(nextButton);
}

// 打开登录弹窗
function openLoginModal() {
    document.getElementById('loginModal').classList.add('active');
    document.getElementById('username').focus();
}

// 关闭登录弹窗
function closeLoginModal() {
    document.getElementById('loginModal').classList.remove('active');
    document.getElementById('loginError').style.display = 'none';
}

// 处理登录
async function handleLogin() {
    const username = document.getElementById('username').value;
    const password = document.getElementById('password').value;
    
    try {
        // 发送请求到实际API接口
        const response = await fetch('http://localhost:3000/admin');
        
        if (!response.ok) {
            throw new Error(`获取管理员信息失败: ${response.status}`);
        }
        
        // 获取原始响应数据
        const responseData = await response.json();
        
        // 调试日志：查看原始响应结构
        console.log('API原始响应数据:', responseData);
        
        // 尝试从可能的嵌套结构中提取管理员数据
        let adminUser = null;
        
        // 情况1：直接返回管理员数组
        if (Array.isArray(responseData) && responseData.length > 0) {
            adminUser = responseData[0];
        } 
        // 情况2：返回 { admin: [...] } 结构
        else if (responseData && Array.isArray(responseData.admin) && responseData.admin.length > 0) {
            adminUser = responseData.admin[0];
        }
        // 情况3：其他可能的结构（根据实际情况调整）
        else if (responseData && responseData.data && Array.isArray(responseData.data)) {
            adminUser = responseData.data[0];
        }
        
        // 验证是否成功提取管理员数据
        if (!adminUser || !adminUser.username || !adminUser.password) {
            throw new Error('无法从API响应中提取有效的管理员数据');
        }
        
        // 验证用户名和密码
        if (username === adminUser.username && password === adminUser.password) {
            // 登录成功
            isAdminLoggedIn = true;
            localStorage.setItem('adminLoggedIn', 'true');
            document.getElementById('adminLoginLink').textContent = '退出登录';
            closeLoginModal();
            loadMessages();
            showNotification('登录成功');
        } else {
            // 登录失败
            document.getElementById('loginError').style.display = 'block';
        }
    } catch (error) {
        console.error('登录验证失败:', error);
        showNotification('登录验证失败，请稍后再试', 'error');
    }
}
// 退出登录
function logoutAdmin() {
    isAdminLoggedIn = false;
    localStorage.removeItem('adminLoggedIn');
    document.getElementById('adminLoginLink').textContent = '管理员登录';
    loadMessages(); // 重新加载留言以隐藏回复框
    showNotification('已退出登录');
}

// 检查管理员登录状态
function checkAdminLoginStatus() {
    isAdminLoggedIn = localStorage.getItem('adminLoggedIn') === 'true';
    document.getElementById('adminLoginLink').textContent = isAdminLoggedIn ? '退出登录' : '管理员登录';
}

// 显示通知
function showNotification(message, type = 'success') {
    // 创建通知元素
    const notification = document.createElement('div');
    notification.className = `fixed top-4 right-4 px-6 py-3 rounded-lg shadow-lg z-50 transition-all duration-300 transform translate-x-full ${
        type === 'error' ? 'bg-red-500 text-white' : 'bg-green-500 text-white'
    }`;
    notification.textContent = message;
    
    // 添加到页面
    document.body.appendChild(notification);
    
    // 触发动画
    setTimeout(() => {
        notification.classList.remove('translate-x-full');
    }, 10);
    
    // 自动关闭
    setTimeout(() => {
        notification.classList.add('translate-x-full');
        setTimeout(() => {
            document.body.removeChild(notification);
        }, 300);
    }, 3000);
}

// 页面加载完成后初始化应用
document.addEventListener('DOMContentLoaded', initApp);
    </script>
</body>
</html>
    

